package dimension.starry.gui.Bar;

import com.mojang.blaze3d.systems.RenderSystem;
import dimension.starry.StarryDimension;
import dimension.starry.entity.MonsterLevel;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.predicate.entity.EntityPredicates;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Vec3d;

import java.util.List;

/**
 * @author 150149
 */
@Environment(EnvType.CLIENT)
public class HealthBar {

    private static final Identifier HUD = new Identifier(
        StarryDimension.MOD_ID, "textures/gui/monster_health_back.png");
    private static final Identifier HUD2 = new Identifier(
        StarryDimension.MOD_ID, "textures/gui/monster_health_front.png");
    private static long lastTime = 0;
    private static LivingEntity target;

    public static void onHudRender(DrawContext drawContext, float tickDelta) {
        ClientPlayerEntity player = MinecraftClient.getInstance().player;
        if (player == null) {
            return;
        }

        if (System.currentTimeMillis() - lastTime > 500) {
            target = getLookingAt(player);
            lastTime = System.currentTimeMillis();
        }
        if (target != null && !target.equals(player)) {
            render(drawContext, target);
        }
    }

    private static LivingEntity getLookingAt(PlayerEntity playerEntity) {
        int scanDistance = 16;
        LivingEntity maxCosEntity = null;
        double maxCos = 0;
        Box box = new Box(
            playerEntity.getBlockX() - scanDistance, playerEntity.getBlockY() - scanDistance,
            playerEntity.getBlockZ() - scanDistance, playerEntity.getBlockX() + scanDistance,
            playerEntity.getBlockY() + scanDistance, playerEntity.getBlockZ() + scanDistance
        );
        List<LivingEntity> livingEntityList = playerEntity.getEntityWorld().getEntitiesByClass(LivingEntity.class, box,
            EntityPredicates.VALID_LIVING_ENTITY
        );
        for (LivingEntity livingEntity : livingEntityList) {
            Vec3d playerViewVector = playerEntity.getRotationVec(1.0F).normalize();
            Vec3d playerToTargetVector = new Vec3d(
                livingEntity.getBlockX() - playerEntity.getBlockX(), livingEntity.getEyeY() - playerEntity.getEyeY(),
                livingEntity.getBlockZ() - playerEntity.getBlockZ()
            );
            playerToTargetVector = playerToTargetVector.normalize();
            double cos = playerViewVector.dotProduct(playerToTargetVector);
            if (cos < 0) {
                cos = -cos;
            }
            if (cos > maxCos && cos > 0.9396 && playerEntity.canSee(livingEntity)) {
                maxCosEntity = livingEntity;
                maxCos = cos;
            }
        }
        return maxCosEntity;
    }

    public static void render(DrawContext drawContext, LivingEntity livingEntity) {
        RenderSystem.clearColor(1.0F, 1.0F, 1.0F, 1.0F);
        int textureWidth = 128;
        int textureHeight = 40;
        double percentage = livingEntity.getHealth() / livingEntity.getMaxHealth();
        TextRenderer textRenderer = MinecraftClient.getInstance().textRenderer;
        if (percentage > 1) {
            percentage = 1;
        }
        drawContext.drawTexture(
            HUD2, 0, 0, 0, 0, (int) (textureWidth * percentage), textureHeight, (int) (textureWidth * percentage),
            textureHeight
        );
        drawContext.drawTexture(HUD, 0, 0, 0, 0, textureWidth, textureHeight, textureWidth, textureHeight);
        int level = MonsterLevel.getLevelFromEntity(livingEntity);
        String entityName =
            level == 0 ? livingEntity.getDisplayName().getString() : livingEntity.getDisplayName().getString() +
                Text.translatable("starry_dimension.gui.message.monster_level", level).getString();
        drawContext.drawCenteredTextWithShadow(textRenderer, entityName, 50, 10, 16777215);
        int health = livingEntity.getHealth() >
            livingEntity.getMaxHealth() ? (int) livingEntity.getMaxHealth() : (int) livingEntity.getHealth();
        String healthString = health + "/" + (int) livingEntity.getMaxHealth();
        drawContext.drawCenteredTextWithShadow(textRenderer, healthString, 60, 20, 16777215);
    }
}
